//
//  registerViewController.m
//  coldjoke-ios-client
//
//  Created by lai on 12-9-25.
//
//

#import "RegisterViewController.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "RegexKitLite.h"
#import "RegisterDoneViewController.h"
#import "UserManager.h"
#import "NetWorkManager.h"

@interface RegisterViewController ()

@end

@implementation RegisterViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc {
    PP_RELEASE(hudLoading);
    PP_RELEASE(registerBtn);
    PP_RELEASE(email);
    PP_RELEASE(password);
    PP_RELEASE(registerBgImageView);
    PP_RELEASE(registerUserImage);
    PP_RELEASE(registerPasswordImage);
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationController.navigationBar.backgroundColor =[UIColor clearColor]; //导航上那条黑线的原因在这里
    self.navigationController.view.layer.cornerRadius = 4;
    self.navigationController.view.layer.masksToBounds = YES;
    self.navigationController.navigationBar.layer.cornerRadius = 4;
    self.navigationController.navigationBar.layer.masksToBounds = YES;

    baseTitle.text = @"注册";

    UIButton* menuBtn= [[[UIButton alloc] initWithFrame:CGRectMake(0.0, 0.0, 44.0, 44.0)] autorelease];
    [menuBtn setBackgroundImage:[UIImage imageNamed:@"nav_bar_back_1.png"] forState:UIControlStateNormal];
    [menuBtn setBackgroundImage:[UIImage imageNamed:@"nav_bar_back_2.png"] forState:UIControlStateHighlighted];
    [menuBtn addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *menuBarBtn = [[[UIBarButtonItem alloc] initWithCustomView:menuBtn] autorelease];
    [self.navigationItem setLeftBarButtonItem:menuBarBtn];
    
    
//    UIImage *registerBgNormal = nil;
//    UIImage *registerBgClick = nil;
//    float version = [[[UIDevice currentDevice] systemVersion] floatValue];
//    if (version >= 5.0){
//        registerBgNormal = [[UIImage imageNamed:@"input_click_1.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10)];
//        registerBgClick = [[UIImage imageNamed:@"input_click_2.png"] resizableImageWithCapInsets:UIEdgeInsetsMake(10, 10, 10, 10)];
//    }else{
//        registerBgNormal = [[UIImage imageNamed:@"input_click_1.png"] stretchableImageWithLeftCapWidth:21 topCapHeight:14];
//        registerBgClick = [[UIImage imageNamed:@"input_click_2.png"] stretchableImageWithLeftCapWidth:21 topCapHeight:14];
//    }
//    [registerBtn setBackgroundImage:registerBgNormal forState:UIControlStateNormal];
//    [registerBtn setBackgroundImage:registerBgClick forState:UIControlStateHighlighted];
    
    UIImage *registerBgImage = [[UIImage imageNamed:@"login_bg.png"] stretchableImageWithLeftCapWidth:15 topCapHeight:21];
    registerBgImageView.image = registerBgImage;
    
    UIImage *registerBgImageOne = [[UIImage imageNamed:@"login_btn_1.png"] stretchableImageWithLeftCapWidth:5 topCapHeight:21];
    UIImage *registerBgImageTwo = [[UIImage imageNamed:@"login_btn_2.png"] stretchableImageWithLeftCapWidth:5 topCapHeight:21];
    [registerBtn setBackgroundImage:registerBgImageOne forState:UIControlStateNormal];
    [registerBtn setBackgroundImage:registerBgImageTwo forState:UIControlStateHighlighted];

    [password setSecureTextEntry:YES];
    
    email = [[UITextField alloc] initWithFrame:CGRectMake(registerUserImage.frame.origin.x +40, registerUserImage.frame.origin.y-8, 230, 40)];
    email.delegate = self;
    email.keyboardType = UIKeyboardTypeEmailAddress;
    email.returnKeyType = UIReturnKeyNext;
    email.borderStyle = UITextBorderStyleNone;
    email.contentVerticalAlignment= UIControlContentVerticalAlignmentCenter;
    email.placeholder = @"邮箱地址";
    email.returnKeyType = UIReturnKeyNext;
    [email addTarget:self action:@selector(textFieldGoToNext:) forControlEvents:UIControlEventEditingDidEndOnExit];

    password = [[UITextField alloc] initWithFrame:CGRectMake(registerPasswordImage.frame.origin.x +40, registerPasswordImage.frame.origin.y-8, 230, 40)];
    password.delegate = self;
    password.userInteractionEnabled = YES;
    password.returnKeyType = UIReturnKeyDone;
    password.borderStyle = UITextBorderStyleNone;
    password.contentVerticalAlignment= UIControlContentVerticalAlignmentCenter;
    password.placeholder = @"密码";
    [password setSecureTextEntry:YES];

    [password addTarget:self  action:@selector(textFieldGoToNext:)  forControlEvents:UIControlEventEditingDidEndOnExit];
    
    [self.view addSubview:email];
    [self.view addSubview:password];
}

- (void)viewDidUnload
{
    PP_RELEASE(hudLoading);
    PP_RELEASE(registerBtn);
    PP_RELEASE(email);
    PP_RELEASE(password);
    PP_RELEASE(registerBgImageView);
    PP_RELEASE(registerUserImage);
    PP_RELEASE(registerPasswordImage);
    [super viewDidUnload];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [email becomeFirstResponder];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(void)textFieldGoToNext:(id)sender
{
    if( sender == email ){
        [sender resignFirstResponder];
        [password becomeFirstResponder];
    }else{
        [sender resignFirstResponder];
    }
}

- (IBAction)doRegister
{
    [email resignFirstResponder];
    [password resignFirstResponder];
    
    //邮箱验证
    if (![email.text isMatchedByRegex:@"^(\\w)+(\\.\\w+)*@(\\w)+((\\.\\w+)+)$"]) {
        [self baseShowInfoHud:NSLocalizedString(@"请输入正确的邮箱", @"") andIsTop:YES];
        [email becomeFirstResponder];
        return;
    }
    //密码验证
    if (![password.text isMatchedByRegex:@"^\\S{6,}$"]) {
        [self baseShowInfoHud:NSLocalizedString(@"密码不少于6位", @"") andIsTop:YES];

        [password becomeFirstResponder];
        password.text = nil;
        return;
    }

    HAS_NO_NETWORK(self);

    UserManager *tUserManager = [UserManager sharedInstance];
    tUserManager.email = email.text;
    tUserManager.password = password.text;
    
    Log(@"navigationController:%@ ",self.navigationController);
    RegisterDoneViewController *RegisterController = [[RegisterDoneViewController alloc]initWithNibName:@"RegisterDoneViewController" bundle:nil];
    [self.navigationController pushViewController:RegisterController animated:YES];

    
    
//    hudLoading = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//    hudLoading.labelText = @"正在注册...";
//    hudLoading.alpha = 0.7;
//    [self.view.window addSubview:hudLoading];
//       dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        UserManager *tUserManager = [UserManager sharedInstance];
//        BOOL succ = [tUserManager registerWithEmail:tUserManager.email password:tUserManager.password username:username.text];
//        dispatch_async(dispatch_get_main_queue(), ^{
//            if(!succ){
//                [UserManager sharedInstance].password = nil;
//                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"注册失败" message:[UserManager sharedInstance].registerErrInfo delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
//                alert.tag = 0;
//                [alert show];
//            }else{
//                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"注册成功" message:[UserManager sharedInstance].registerErrInfo delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil ];
//                alert.tag = 1;
//                [alert show];
//            }
//            [hudLoading hide:YES];
//        });
//    });
}

-(void) back:(id)sender
{
    [email resignFirstResponder];
    [password resignFirstResponder];
    
    if (self.navigationController) {
        [self.navigationController popViewControllerAnimated:YES];
    }
    
    if ([self respondsToSelector:@selector(presentingViewController)]) {
        
        if (self.presentedViewController) {
            [[self presentedViewController] dismissModalViewControllerAnimated:YES];
        }
        else {
            [self dismissModalViewControllerAnimated:YES];
        }
    }else {
        [[self parentViewController] dismissModalViewControllerAnimated:YES];
    }

}

@end
